﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using WMM.Tapioca.Utilities;
using System.Text.RegularExpressions;

namespace WMM.Tapioca.Formula.Aspects
{
    /// <summary>
    /// A concept rule is an aspect rule that addresses the concept aspect and 
    /// that is expressed by a <formula:concept> element. 
    /// </summary>
    public class ConceptAspect : Aspect
    {
        private XName qname;

        /// <returns> The QName contained by the <formula:qname> element. </returns>
        public XName Qname
        {
            get { return qname; }
            set { qname = value; }
        }

        private string qnameExpression;

        /// <returns> The XPath expression the <formula:qnameExpression> . </returns>
        public string QnameExpression
        {
            get { return qnameExpression; }
            set { qnameExpression = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public ConceptAspect(XElement conceptAspect, XbrlDocument parentDocument)
        {
            XElement aspect = conceptAspect.Parent;

            if (aspect.Attribute("source") != null)
            {
                this.Source = aspect.Attribute("source").Value;
            }

            if (conceptAspect.Attribute("source") != null)
            {
                this.Source = conceptAspect.Attribute("source").Value;
            }

            XElement conceptQname = conceptAspect.Element(formula + "qname");

            if (conceptQname != null)
            {
                string prefix = conceptQname.Value.GetPrefix();
                string localName = conceptQname.Value.GetLocalName();

                XNamespace ns = "";

                if (prefix != string.Empty)
                {
                    ns = parentDocument.ThisXDocument.Root.GetNamespaceOfPrefix(prefix);
                }

                this.Qname = ns + localName;
            }

            XElement conceptQnameExpression = conceptAspect.Element(formula + "qnameExpression");

            if (conceptQnameExpression != null)
            {
                string expression = conceptQnameExpression.Value;
                expression = expression.TrimEnd().TrimStart();
                expression = Regex.Replace(expression, @"\s+", " ");
                this.QnameExpression = expression;
            }
        }
    }
}
